package com.mall.pay.controller;


import com.alipay.api.AlipayApiException;
import com.alipay.easysdk.factory.Factory;
import com.mall.api.pay.dto.PayDTO;
import com.mall.common.domain.R;
import com.mall.pay.domain.dto.NotifyDTO;
import com.mall.pay.domain.po.Order;
import com.mall.pay.service.IPayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("payment")
public class PayController {


    @Autowired
    private IPayService payService;

    /**
     * 支付接口, 返回支付宝的表单
     * @param payDTO
     * @return
     * @throws AlipayApiException
     */
    @GetMapping("pay")
    public String pay(PayDTO payDTO) throws AlipayApiException {

        return payService.pay(payDTO);
    }

    /**
     * 支付回调 该接口由支付宝自动调用,记得开启内网穿透
     *
     * @param request 接收参数使用 HttpServletRequest, 因为需要做支付宝的验证签名 需要所有参数
     * @return
     */
    @PostMapping("/notify")
    public String payNotify(HttpServletRequest request) throws Exception {
        // 收集所有请求参数到 Map
        Map<String, String> params = new HashMap<>();
        request.getParameterMap().forEach(
                (key, values) -> params.put(key, values.length > 0 ? values[0] : "")
        );

        // 构建 NotifyDTO
        NotifyDTO notifyData = new NotifyDTO();
        notifyData.setParams(params);
        notifyData.setTradeStatus(params.get("trade_status"));
        notifyData.setOutTradeNo(params.get("out_trade_no"));
        notifyData.setGmtPayment(params.get("gmt_payment"));
        notifyData.setTradeNo(params.get("trade_no"));

        return payService.payNotify(notifyData);
    }

    /**
     * 退款接口
     * @return
     */
    @PostMapping("/refund")
    public String refund(){


        return "success";
    }




}
